package ta.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ta.dao.UserDao;
import ta.pojo.User;

@WebServlet(name = "RegisterServlet",urlPatterns="/RegisterServlet")
public class RegisterServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        register(request, response);
    }

    // 注册
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String repwd=request.getParameter("confirm-password");
        User user = new User();
        User user1 = new User();
        user.setUsername(username);
        user1.setUsername(username);
        user.setUserpwd(repwd);
        UserDao dao = new UserDao();
        boolean nameIsHave=dao.selectByUsername(user1);
        PrintWriter w=response.getWriter();
        if (password.equals(repwd)){
            if(!nameIsHave){
                dao.register(user);
                // 跳转到登录页面
                response.getWriter().print("<script>alert('注册成功！')</script>");
                response.setHeader("refresh","0.1;url=login.jsp");
            }else {
                response.getWriter().print("<script>alert('用户名被占用！')</script>");
                response.setHeader("refresh","0.1;url=login.jsp");
            }
        } else {
            response.getWriter().print("<script>alert('两次密码输入不一致！')</script>");
            response.setHeader("refresh","0.1;url=login.jsp");
        }


    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
